package com.shuai.chatroom.common;

import com.shuai.chatroom.exception.ControllerException;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.UUID;

public class PwdSaltUtils {
    public static String encrypt(String inputPassword) throws ControllerException {
        if (!StringUtils.hasLength(inputPassword)) {
            throw new ControllerException("密码为空！");
        }
        //先生成一个32位的UUID
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        //将其与密码组装进行加密
        String encrypted = DigestUtils.md5DigestAsHex((uuid + inputPassword).getBytes());
        //将组装并加密后的密码在拼上生成的UUID加上一个分隔符返回，共计65位
        return uuid + AppConstant.SEPARATOR + encrypted;
    }


    private static String encrypt(String inputPassword, String uuid) {
        String encrypted = DigestUtils.md5DigestAsHex((uuid + inputPassword).getBytes());
        //将组装并加密后的密码在拼上生成的UUID加上一个分隔符返回，共计65位
        return uuid + AppConstant.SEPARATOR + encrypted;
    }

    public static boolean verify(String inputPassword, String encryptedPwdFromDB) throws ControllerException {
        if (!StringUtils.hasLength(inputPassword) || !StringUtils.hasLength(encryptedPwdFromDB) || encryptedPwdFromDB.length() != AppConstant.PWD_LENGTH) {
            throw new ControllerException("校验失败，密码格式错误！");
        }
        //取得密码对应的uuid
        String uuid = encryptedPwdFromDB.split("\\$")[0];
        //按照相同的加密方式进行加密
        String confirmPwd = encrypt(inputPassword, uuid);
        System.out.println(confirmPwd);
        return confirmPwd.equals(encryptedPwdFromDB);
    }
}
